package org.example.socket.bio;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicLong;

public class BioClient {

    private static final int LOOP_TIMES = 5000;

    private static final AtomicLong clientId = new AtomicLong(0);

    private static final ExecutorService executor = Executors.newFixedThreadPool(10);

    public static void main(String[] args) throws InterruptedException {
        long startT = System.currentTimeMillis();
        CountDownLatch countDownLatch = new CountDownLatch(LOOP_TIMES);
        for (int i = 0; i < LOOP_TIMES; i++) {
            executor.execute(() -> {
                try {
                    send();
                    countDownLatch.countDown();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
        }
        countDownLatch.await();
        System.out.println("total cost:" + (System.currentTimeMillis() - startT) + " ms.");
        executor.shutdown();
    }

    private static void send() throws IOException {

        try (Socket socket = new Socket("localhost", 8888);
             InputStream is = socket.getInputStream();
             OutputStream os = socket.getOutputStream()) {
            os.write(("I am client " + clientId.incrementAndGet()).getBytes(StandardCharsets.UTF_8));
            os.flush();
            byte[] b = new byte[256];
            if (-1 != is.read(b)) {
                System.out.println("recv server msg:" + new String(b));
            }
        }
    }
}
